import md5 from './md5.js';
import config from '@/config/config.js';
import Request from './luch-request/index.js';
import store from '@/store/index.js';

class HttpRequest {
  constructor(baseUrl = config.baseUrl) {
    this.baseUrl = baseUrl;
    this.queue = {};
    this.kSalt = config.kSalt;
    this.shouldEncryptParams = false;
  }
  getDefaultConfig() {
    const defaultConfig = {
      baseURL: this.baseUrl,
      method: 'post',
      showLoading: true,
      timeout: 60000,
      withCredentials: true
    };
    return defaultConfig;
  }
  // 参数处理
  paramsHandler(params) {
    params = params || {};
    // 加上默认参数
    // if (store.state.vx_token) {
    //   params['token'] = store.state.vuex_token;
    // }

    // 是否需要加密
    if (!this.shouldEncryptParams) {
      return params;
    }
    // 1.加上时间戳
    params['timestamp'] = Date.parse(new Date()) / 1000;
    // 2.从大到小排序
    const keys = Object.keys(params);
    keys.sort((a, b) => {
      return b.localeCompare(a);
    });
    // 3.加盐
    var items = [];
    keys.forEach(function (key) {
      if (key != 'needUid') {
        items.push(`${key}=${encodeURIComponent(params[key])}`);
      }
    });
    items.push(this.kSalt);
    // 4.md5
    params['sign'] = md5.hexMD5(items.join('&'));
    return params;
  }
  // 拦截器
  interceptors(instance, options) {
    instance.interceptors.request.use((config) => {
      if (options.showLoading) {
        if (!Object.keys(this.queue).length) {
          uni.showLoading({
            title: '加载中',
            mask: true,
          });
        }
        this.queue[options.url] = true;
      }
      if (store.state.vx_token) {
        config.header['Token'] = store.state.vx_token;
      }
      // 设置请求方式
      config.header['content-type'] = options.contentType == 'form' ? 'application/x-www-form-urlencoded' : 'application/json';
      console.log(`${options.url} >>>`);
      if (options.method === 'get') {
        console.log(options.params);
      } else {
        console.log(options.data);
      }
      return config;
    });

    instance.interceptors.response.use(
      (res) => {
        delete this.queue[options.url];
        if (Object.keys(this.queue).length === 0) {
          uni.hideLoading();
        }
        const data = res.data;
        console.log(data);
        switch (data.code){
          case 200: {
            // 请求正常
            return data.data;
          }
          case 201: {
            // 请求正常，并提示信息
            uni.showToast({
              icon: 'none',
              title: data.desc
            });
            return data.data;
          }
          case 400: {
            // 错误
            uni.showToast({
              icon: 'none',
              title: data.desc
            });
            return Promise.reject(data.desc);
          }
          case 500: {
            // 退出登录
            store.commit('logout');
          }
          default: {
            // 错误
            uni.showToast({
              icon: 'none',
              title: data.desc
            });
            return Promise.reject(data.desc);
          } 
        }
      },
      (err) => {
        uni.showToast({
          icon: 'none',
          title: '网络异常',
        });
        delete this.queue[options.url];
        if (Object.keys(this.queue).length === 0) {
          uni.hideLoading();
        }
        return Promise.reject(err);
      }
    );
  }
  
  request(options) {
    options = Object.assign(this.getDefaultConfig(), options);
    const instance = new Request(options);
    this.interceptors(instance, options);
    if (options.method === 'get') {
      return instance[options.method](
        options.url,
        { params: this.paramsHandler(options.data) },
      );
    } else {
      return instance[options.method](
        options.url,
        this.paramsHandler(options.data)
      );
    }
  }
}

export default HttpRequest;
